<?php 
namespace App\Repositories;

use App\Models\Address;
use App\Exceptions\InvalidException;
class AddressRepo
{
    public function getList($user_id,$where=[],$page=15)
    {
        return Address::where('user_id',$user_id)->get()->toArray();
        // return Address::where(function($query) use ($user_id,$where){
            // $query->where('user_id',$user_id);
        // })->get()->toArray();
    }

    public function getDefault($user_id)
    {
         return   Address::where('user_id',$user_id)->where('default',1)->first();

    }
    public function create($data)
    {
    	try{
            $address = Address::create($data);
            if($data['default'] == 1) {
            	Address::where('user_id',$data['user_id'])->where('id','<>',$address->id)->update(['default'=>0]);
            }
        }catch(\Exception $e) {
            throw new InvalidException($e->getMessage());
        }
    }
    public function update($user_id,$id,$data)
    {

    	try{
            $address = Address::where('id',$id)->first();
            if($address) {
            	  $address->update($data);
            }
          
            // ($data);
            // if($data['default'] == 1) {
            // 	Address::where('user_id',$data['user_id'])->where('id','<>',$address->id)->update(['default'=>0]);
            // }
        }catch(\Exception $e) {
            throw new InvalidException($e->getMessage());
        }
    }
    public function del($id,$user_id) 
    {
    	 $address = Address::where('id',$id)->where('user_id',$user_id)->first();
         if(!$address) {
            throw new InvalidException("地址不存在");
         }
    	 $address->delete();
    }
}